package cn.stylefeng.guns.modular.recy.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONArray;
import cn.stylefeng.guns.core.util.DecimalUtil;
import cn.stylefeng.guns.modular.system.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.druid.sql.visitor.functions.Bin;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.roses.core.base.controller.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
import javax.servlet.http.*;
import javax.xml.crypto.Data;

import me.chanjar.weixin.mp.api.*;
import com.github.binarywang.wxpay.service.*;
import cn.stylefeng.guns.modular.recy.service.*;
import cn.stylefeng.guns.modular.recy.vo.wx.*;
import org.apache.commons.lang3.*;
import cn.stylefeng.guns.core.common.exception.*;
import cn.stylefeng.roses.kernel.model.exception.*;
import cn.stylefeng.guns.core.common.constant.*;
import com.baomidou.mybatisplus.core.conditions.query.*;
import cn.stylefeng.roses.core.reqres.response.*;
import org.apache.commons.lang3.math.*;
import java.io.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.*;
import cn.stylefeng.guns.modular.weixin.utils.*;
import cn.stylefeng.guns.modular.miniapp.config.*;
import me.chanjar.weixin.common.error.*;
import me.chanjar.weixin.mp.bean.result.*;
import cn.binarywang.wx.miniapp.api.*;
import cn.binarywang.wx.miniapp.bean.*;
import cn.stylefeng.guns.modular.recy.utils.*;
import cn.hutool.core.convert.*;
import cn.hutool.http.*;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.hutool.core.date.*;
import cn.hutool.core.util.*;
import cn.stylefeng.guns.modular.recy.vo.*;

import java.math.BigDecimal;
import java.util.concurrent.ConcurrentHashMap;
import java.util.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

@Controller
@RequestMapping({ "/app" })
public class AppController extends BaseController
{

    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private HttpServletRequest request;


    @Autowired
    private WxMpService wxService;

    @Autowired
    private WxPayService wxPayService;


    @Autowired
    private AppVersionInfoService appVersionInfoService;

    @Autowired
    private BinsService binsService;

    @Autowired
    private BinsNoCreator binsNoCreator;
    @Autowired
    private WasteTypeService wasteTypeService;
    @Autowired
    private OrderFormService orderFormService;
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private CommandOrderService commandOrderService;
    @Autowired
    private WasteStationService wasteStationService;

    @Autowired
    private UserBinService userBinService;

    @Autowired
    private UserService userService;

    @Autowired
    private IntegrateInfoService integrateInfoService;

    public static Map<String,String> sessionMacMap = new ConcurrentHashMap<>();

    public void checkSign(){
        HttpServletRequest httpServletRequest = this.getHttpServletRequest();
        String sign = httpServletRequest.getHeader("sign");
        String timestamp = httpServletRequest.getHeader("timestamp");
        String noneStr = httpServletRequest.getHeader("noneStr");
        String deviceId = httpServletRequest.getHeader("deviceId");
    }
    public WxLogin checkToken() {
        System.out.println("检测token");
        final String token = this.request.getHeader("token");
        if (!StringUtils.isNotBlank((CharSequence)token)) {
            throw new ServiceException((AbstractBaseExceptionEnum)BizExceptionEnum.TOKEN_ERROR);
        }
        final WxLogin wxLogin = Const.tokenMap.get(token);
        if (wxLogin == null) {
            throw new ServiceException((AbstractBaseExceptionEnum)BizExceptionEnum.TOKEN_ERROR);
        }
        final Date expireTime = wxLogin.getExpireTime();
        if (expireTime.getTime() >= new Date().getTime()) {
            return wxLogin;
        }
        throw new ServiceException((AbstractBaseExceptionEnum)BizExceptionEnum.TOKEN_ERROR);
    }

    @RequestMapping({ "/getUserDetail" })
    @ResponseBody
    public Object getUserDetail() {
        final String openId = this.checkToken().getOpenId();
        if (!StringUtils.isNotBlank((CharSequence)openId)) {
            return new ErrorResponseData("用户信息获取失败!");
        }
        final WechatUser user = this.wechatUserService.findByOpenId(openId);
        if (user != null) {
            final WechatUserVO userVO = EntityBind.bind(user, WechatUserVO.class);
            final Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("baseInfo", userVO);
            return new SuccessResponseData(userVO);
        }
        return new ErrorResponseData("用户信息获取失败!");
    }
    

    

    
    @RequestMapping({ "/bind/{appid}/{maCode}" })
    public Object bind(@PathVariable("appid") final String appid, @PathVariable("maCode") final String maCode, final String code, final Model model) {
        final boolean switchover = this.wxService.switchover(appid);
        if (switchover) {
            try {
                final WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
                final String mpOpenId = wxMpOAuth2AccessToken.getOpenId();
                final WechatUser mpUser = this.wechatUserService.getByOpenId(mpOpenId);
                String maOpenIdByCode = null;
                final String maAppId = WxUtils.getDefaultMa();
                final WxMaService wxService = WxMaConfiguration.getMaService(maAppId);
                final WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(maCode);
                maOpenIdByCode = session.getOpenid();
                final WechatUser maUser = this.wechatUserService.getByOpenId(maOpenIdByCode);
                final String userMaOpenId = mpUser.getMiniProgramId();
                if (StringUtils.isBlank((CharSequence)userMaOpenId)) {
                    mpUser.setMiniProgramId(maOpenIdByCode);
                    mpUser.setWechatNickName(maUser.getWechatNickName());
                    mpUser.setAvatarUrl(maUser.getAvatarUrl());
                    mpUser.setPhone(maUser.getPhone());
                    mpUser.setRealName(maUser.getRealName());
                    mpUser.setIdcard(maUser.getIdcard());
                    mpUser.setMpCode(WxUtils.wechatAppConfig.get(appid));
                    mpUser.updateById();
                }
                final String miniProgramId = maUser.getMiniProgramId();
                if (StringUtils.isBlank((CharSequence)miniProgramId)) {
                    maUser.setMiniProgramId(mpOpenId);
                    maUser.updateById();
                }
            }
            catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return "/modular/recy/wechatUser/bind.html";
    }

    @RequestMapping({ "/relativeMp" })
    @ResponseBody
    public Object relativeMp() {
        this.checkToken();
        final String mpId = WxUtils.getDefaultMp();
        return mpId;
    }

    @RequestMapping("/updateInfo")
    @ResponseBody
    public Object updateInfo(int versionCode,String appKey){

        QueryWrapper<AppVersionInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AppVersionInfo::getAppKey,"com.jinbaoty.recyclebins");
        List<AppVersionInfo> list = this.appVersionInfoService.list(queryWrapper);
        if(list.size()>0){
            AppVersionInfo appVersionInfo = list.get(0);
            Map<String, Object> stringObjectMap = BeanUtil.beanToMap(appVersionInfo);
            stringObjectMap.put("code",0);
            stringObjectMap.put("msg","");
            Map<String,Object> updateInfoMap =new HashMap<>();
            for(String key:stringObjectMap.keySet()){
                if(!key.equalsIgnoreCase("id"))
                updateInfoMap.put(StrUtil.upperFirst(key),stringObjectMap.get(key));
            }
            return updateInfoMap;
        }
        return null;
    }
    @RequestMapping("/bannerList")
    @ResponseBody
    public Object bannerList(){
        Map<String, String> sign = getSign();
        Long deviceId = getDeviceId();
        System.out.println("获取广告列表，参数设备ID："+deviceId);
        Bins bins = this.binsService.getById(deviceId);
        String banners = bins.getBanners();
        Set<String> imgWebPathList = new HashSet<>();
        String imgRoot = ControllerUtil.getRealPath("/upload/img");
        if(StringUtils.isNotBlank(banners)) {
            String[] bannerAttr = StringUtils.split(banners, ",");
            File imgDir = new File(imgRoot);
            File parentFile = imgDir.getParentFile().getParentFile();
            for(String banner:bannerAttr){
                if(StringUtils.isNotBlank(banner)){
                    File imgFile = new File(parentFile,banner);
                    if(imgFile.exists()) {
                        imgWebPathList.add(banner);
                    }
                }
            }
        }
        if(imgWebPathList.size()==0) {
            List<String> imgNameList = FileUtil.listFileNames(imgRoot);
            imgNameList.forEach(imgName -> {
                String extension = FilenameUtils.getExtension(imgName);
                if(StringUtils.endsWithAny(StringUtils.lowerCase(extension),"png","jpg","bmp","gif","mp4","avi","rm","rmvb")) {
                    imgWebPathList.add("/upload/img/" + imgName);
                }
            });
        }
        return new SuccessResponseData(imgWebPathList);
    }

    @RequestMapping("/regDevice")
    @ResponseBody
    public Object regDevice(String s){
        String clientIP = ServletUtil.getClientIP(this.getHttpServletRequest());
        sessionMacMap.put(clientIP,s);
        System.out.println("注册设备（IP地址："+clientIP+"）");
        String sessionId = getSession().getId();
        System.out.println("回话ID(注册设备)："+sessionId);
        sessionMacMap.put(sessionId,s);
        System.out.println("注册设备："+s);
        QueryWrapper<Bins> binsQueryWrapper = new QueryWrapper<>();
        binsQueryWrapper.lambda().eq(Bins::getBinsMacAddress,s);
        List<Bins> list = this.binsService.list(binsQueryWrapper);
        if(list.size()>0){
            Bins bins = list.get(0);
            boolean needUpdate = false;
            if(StrUtil.isBlank(bins.getArea())){
                bins.setArea(getArea());
                needUpdate = true;

            }
            if(!new Long(3l).equals(bins.getStatus())) {//非未激活状态，则将回收设备状态置为0(在线)
                bins.setLastUpdateTime(new Date());
                bins.setStatus(0l);
                needUpdate = true;
            }
            if(needUpdate){
                this.binsService.updateById(bins);
            }
            return new SuccessResponseData(bins);
        }else{
            long binsNo = binsNoCreator.incrementAndGet();
            Bins bins = Bins.builder().area(getArea()).binsMacAddress(s).binsNo(binsNo).adminPwd(RandomUtil.randomNumbers(9)).createTime(new DateTime()).status(3l).manageUserId(0l).build();
            bins.insert();
            return new SuccessResponseData(bins);
        }
    }

    private Bins getBinsByMacAddress(String macAddress){
        QueryWrapper<Bins> binsQueryWrapper = new QueryWrapper<>();
        binsQueryWrapper.lambda().eq(Bins::getBinsMacAddress,macAddress);
        List<Bins> list = this.binsService.list(binsQueryWrapper);
        if(list.size()>0){
            return list.get(0);
        }else {
            return null;
        }
    }

    private Long getDeviceId(){
        String deviceIdStr = this.getHttpServletRequest().getHeader("deviceId");
        Long deviceId = Convert.toLong(deviceIdStr, -1l);
        if(deviceId.equals(-1l)){
            String clientIP = ServletUtil.getClientIP(this.getHttpServletRequest());
            System.out.println("获取设备id（IP地址："+clientIP+"）");
            String macAddress = sessionMacMap.get(clientIP);
            long waitTime = 200;
            while(StringUtils.isBlank(macAddress) && waitTime<800){
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                macAddress = sessionMacMap.get(clientIP);
                waitTime+=200;
            }
            if(StringUtils.isNotBlank(macAddress)){
                System.out.println("获取到设备Mac："+macAddress);
                Bins binsByMacAddress = getBinsByMacAddress(macAddress);
                if(binsByMacAddress!=null){
                    return binsByMacAddress.getId();
                }
            }else{
                System.out.println("获取设备mac失败！");
            }

        }
        return deviceId;
    }

    @RequestMapping("/wasteTypeList")
    @ResponseBody
    public Object wasteTypeList(){
        Map<String, String> sign = getSign();
        Long deviceId = getDeviceId();
        System.out.println("获取回收物类别列表，参数设备ID："+deviceId);
        Bins bins = this.binsService.getById(deviceId);
        String wasteTypes = StringUtils.trim(bins.getWasteTypes());
        List<WasteType> list = new ArrayList<>();
        if(StringUtils.isNotBlank(wasteTypes)){
            QueryWrapper<WasteType> wasteTypeQueryWrapper = new QueryWrapper<>();
            String[] wasteTypeIdsStr = wasteTypes.split(",");
            Long[] wasteTypeIds = Convert.toLongArray(wasteTypeIdsStr);
            wasteTypeQueryWrapper.lambda().in(WasteType::getId,wasteTypeIds);
            list = this.wasteTypeService.list(wasteTypeQueryWrapper);
        }else {
            list = this.wasteTypeService.list();
        }
       // List<WasteTypeVO> typeVOList = EntityBind.bind(list, WasteTypeVO.class);
        return new SuccessResponseData(list);
    }

    @RequestMapping("/orderList")
    @ResponseBody
    public Object orderListForBins(@RequestHeader Long deviceId){
        QueryWrapper<OrderForm> orderFormQueryWrapper =new QueryWrapper<>();
        orderFormQueryWrapper.lambda().eq(OrderForm::getBinsId,deviceId).eq(OrderForm::getState,DictUtils.me().id("order_form_state::create"));
        OrderForm orderForm = this.orderFormService.getOne(orderFormQueryWrapper, false);
        if(orderForm==null){
            return new ErrorResponseData("暂时无人下单！");
        }else{
            return new SuccessResponseData(EntityBind.bind(orderForm,OrderFormVO.class));
        }
    }

    @RequestMapping("/checkCardNo")
    @ResponseBody
    public Object checkCardNo(String cardNo){
        QueryWrapper<WechatUser> wechatUserQueryWrapper = new QueryWrapper<>();
        wechatUserQueryWrapper.lambda().eq(WechatUser::getCardNo,cardNo);
        List<WechatUser> userList = this.wechatUserService.list(wechatUserQueryWrapper);
        if(userList.size()>0){
            return new SuccessResponseData(userList.get(0).getId());
        }else {
            return new ErrorResponseData("卡号尚未绑定公众号，请先扫码绑定！");
        }
    }

    @RequestMapping("/createOrder")
    @ResponseBody
    public Object createOrderForm(@RequestHeader Long deviceId,String cardNo,Long wasteTypeId){
        QueryWrapper<WechatUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(WechatUser::getCardNo,cardNo);
        List<WechatUser> userList = this.wechatUserService.list(userQueryWrapper);
        if(userList.size()>0){
            WechatUser user = userList.get(0);
            QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(OrderForm::getBinsId,deviceId).eq(OrderForm::getUserId,user.getId()).eq(OrderForm::getState, DictUtils.me().id("order_form_state::create"));
            List<OrderForm> orderFormList = this.orderFormService.list(queryWrapper);
            OrderForm orderForm = null;
            if(orderFormList.size()<=0) {
                orderForm = OrderForm.builder().userId(user.getId()).wasteId(wasteTypeId).binsId(deviceId).createTime(new DateTime()).state(DictUtils.me().id("order_form_state::create")).build();
                orderForm.insert();
            }else{
                //return new ErrorResponseData("存在未完成订单");
                //return new SuccessResponseData(orderFormList.get(0));
                orderForm = orderFormList.get(0);
            }
            return new SuccessResponseData(orderForm);
        }else{
            return new ErrorResponseData("卡号尚未绑定公众号，请先扫码绑定！");
        }
    }

    @RequestMapping("/createOrderFree")
    @ResponseBody
    public Object createOrderFormFree(@RequestHeader Long deviceId,Long wasteTypeId){
        QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrderForm::getBinsId,deviceId).isNull(OrderForm::getUserId).eq(OrderForm::getState, DictUtils.me().id("order_form_state::create"));
        List<OrderForm> orderFormList = this.orderFormService.list(queryWrapper);
        OrderForm orderForm = null;
        if(orderFormList.size()<=0) {
            orderForm = OrderForm.builder().wasteId(wasteTypeId).binsId(deviceId).createTime(new DateTime()).state(DictUtils.me().id("order_form_state::create")).build();
            orderForm.insert();
        }else{
            orderForm = orderFormList.get(0);
        }

        return new SuccessResponseData(orderForm);
    }

    @RequestMapping("/updateOrderWasteType")
    @ResponseBody
    public Object updateOrderWasteType(Long wasteTypeId,Long orderId){
        if(orderId!=null && wasteTypeId!=null) {
            OrderForm orderForm = this.orderFormService.getById(orderId);
            if(!(DictUtils.me().eq("order_form_state::finish",orderForm.getState()) || DictUtils.me().eq("order_form_state::stop",orderForm.getState()))) {
                orderForm.setWasteId(wasteTypeId);
                orderForm.setOrderNo(savePhoto());
                orderForm.insertOrUpdate();
            }
        }
        return new SuccessResponseData();
    }

    @RequestMapping("/toBind")
    public Object toBind(String code,Model model){
        if (this.wxMpService.switchover(WxUtils.getDefaultMp())) {
            try {
                WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxMpService.oauth2getAccessToken(code);
                String openId = wxMpOAuth2AccessToken.getOpenId();
                WechatUser user = this.wechatUserService.getByOpenId(openId);
                model.addAttribute("user",user);
                return "/modular/recy/wechatUser/bindCardNo.html";
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("/bindCardNo")
    @ResponseBody
    public Object bindCardNo(Long userId,String cardNo){
        WechatUser user = this.wechatUserService.getById(userId);
        if(user!=null){
            if(StrUtil.isBlank(user.getCardNo()) && StrUtil.isNotBlank(cardNo)){
                user.setCardNo(cardNo);
                user.insertOrUpdate();
                return new SuccessResponseData();
            }
        }
        return new ErrorResponseData("尚未注册或卡号不正确");
    }

    @RequestMapping("/submitOrder")
    @ResponseBody
    public Object submitOrder(Long orderId,Long state,Long wasteWeight,String errorMsg){
        System.out.println("orderId:"+orderId+",state:"+state+","+wasteWeight);
        OrderForm orderForm = this.orderFormService.getById(orderId);
        if (ObjectUtil.equal(state,0x7bl)) {//stop
            orderForm.setState(DictUtils.me().id("order_form_state::stop"));
        }else if(ObjectUtil.equal(state,0x7cl)){//finish
            orderForm.setState(DictUtils.me().id("order_form_state::finish"));
        }
        orderForm.setWasteWeight(wasteWeight);
        orderForm.setErrorMsg(errorMsg);
        orderForm.setFinishTime(new Date());
        orderForm.setPrice(0l);
        Long binsId = orderForm.getBinsId();
        Bins bins = this.binsService.getById(binsId);
        Map<String,String> returnMap = new HashMap<>();
        Long wasteId = orderForm.getWasteId();
        WasteType wasteType = this.wasteTypeService.getById(wasteId);
        String jifenStr = wasteType.getTypeDesc();
        double rate = NumberUtils.toDouble(jifenStr,50);
        returnMap.put("jifenRate",rate+"");
        returnMap.put("jifen","0");
        if(wasteWeight!=null && wasteWeight>0){
            Long userId = orderForm.getUserId();
            if(userId!=null) {
                WechatUser user = this.wechatUserService.getById(userId);
                double jifen = wasteWeight / rate;
                orderForm.setPrice(new Double(jifen).longValue());
                user.setWithdraw(user.getWithdraw() + jifen);//积分
                user.insertOrUpdate();
                returnMap.put("jifen",jifen+"");
            }
            bins.setManageUserId(ObjectUtil.defaultIfNull(bins.getManageUserId(),0l)+wasteWeight);
            this.binsService.updateById(bins);
        }
        orderForm.insertOrUpdate();
        if(StringUtils.contains(errorMsg,"已满）要求返回：（t），实际返回：")){

            bins.setStatus(2l);//箱已满
            this.binsService.updateById(bins);
        }

        return new SuccessResponseData(returnMap);
    }

    @RequestMapping("/serviceInfo")
    @ResponseBody
    public Object serviceInfo(){
        Dict dict = DictUtils.me().dict("service_info::phone");
        return new SuccessResponseData(dict);
    }

    @RequestMapping("/errorLog")
    @ResponseBody
    public Object errorLog(String error){
        System.err.println(error);
        String realPath = ControllerUtil.getRealPath("/upload/brand");
        File file = new File(realPath,"errorlog.log");
        System.out.println(file.getPath());
        try {
            if(StrUtil.isNotBlank(error)){
                byte[] bytes = error.getBytes("utf-8");
                FileUtil.writeBytes(bytes,file,0,bytes.length,true);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SuccessResponseData("成功保存日志");
    }

    /**
     * 管理模式，验证密码
     * @param deviceId  设备id
     * @param pwd 密码,sha1摘要
     * @return
     */
    @RequestMapping("/checkAdminPwd")
    @ResponseBody
    public Object checkAdminPwd(@RequestHeader Long deviceId,String pwd){
        Bins bins = this.binsService.getById(deviceId);
        if(bins!=null){
            if(StrUtil.equals(pwd, SecureUtil.sha1(bins.getAdminPwd()))){
                if (new Long(3l).equals(bins.getStatus())) {//未激活状态
                    UpdateWrapper<Bins> binsUpdateWrapper = new UpdateWrapper<>();
                    binsUpdateWrapper.lambda().eq(Bins::getId,bins.getId()).set(Bins::getStatus,0l);
                    this.binsService.update(binsUpdateWrapper);
                }
                return new SuccessResponseData(bins);
            }else{
                return new ErrorResponseData("密码不正确！");
            }
        }
        return new ErrorResponseData("密码不正确！");
    }

    @RequestMapping("/createOrderWithPhoto")
    @ResponseBody
    public Object createOrderWithPhoto(@RequestHeader Long deviceId,String cardNo,Long wasteTypeId){
        String fileName = savePhoto();

        if(StrUtil.isBlank(fileName)){
            return new ErrorResponseData("照片上传不成功！");
        }else{
            QueryWrapper<WechatUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().eq(WechatUser::getCardNo,cardNo);
            List<WechatUser> userList = this.wechatUserService.list(userQueryWrapper);
            if(userList.size()>0){
                WechatUser user = userList.get(0);
                QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(OrderForm::getBinsId,deviceId).eq(OrderForm::getUserId,user.getId()).eq(OrderForm::getState, DictUtils.me().id("order_form_state::create"));
                List<OrderForm> orderFormList = this.orderFormService.list(queryWrapper);
                OrderForm orderForm = null;
                if(orderFormList.size()<=0) {
                    orderForm = OrderForm.builder().orderNo(fileName).userId(user.getId()).wasteId(wasteTypeId).binsId(deviceId).createTime(new DateTime()).state(DictUtils.me().id("order_form_state::create")).build();
                    orderForm.insert();
                }else{
                    //return new ErrorResponseData("存在未完成订单");
                    //return new SuccessResponseData(orderFormList.get(0));
                    orderForm = orderFormList.get(0);
                }
                return new SuccessResponseData(orderForm);
            }else{
                return new ErrorResponseData("卡号尚未绑定公众号，请先扫码绑定！");
            }
        }
    }

    @RequestMapping("/createOrderFreeWithPhoto")
    @ResponseBody
    public Object createOrderFreeWithPhoto(@RequestHeader Long deviceId,Long wasteTypeId){
        String fileName = savePhoto();
        if(StrUtil.isBlank(fileName)){
            return new ErrorResponseData("照片上传失败！");
        }
        QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrderForm::getBinsId,deviceId).isNull(OrderForm::getUserId).eq(OrderForm::getState, DictUtils.me().id("order_form_state::create"));
        List<OrderForm> orderFormList = this.orderFormService.list(queryWrapper);
        OrderForm orderForm = null;
        if(orderFormList.size()<=0) {
            orderForm = OrderForm.builder().orderNo(fileName).wasteId(wasteTypeId).binsId(deviceId).createTime(new DateTime()).state(DictUtils.me().id("order_form_state::create")).build();
            orderForm.insert();
        }else{
            orderForm = orderFormList.get(0);
        }

        return new SuccessResponseData(orderForm);
    }
    private String savePhoto(){
        final HttpServletRequest request = this.getHttpServletRequest();
        final String header = request.getHeader("content-type");
        if (StringUtils.containsIgnoreCase((CharSequence)header, (CharSequence)"multipart/form-data")) {
            final StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
            final MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            final Map<String, MultipartFile> fileMap = (Map<String, MultipartFile>)multipartRequest.getFileMap();
            final boolean file1 = fileMap.containsKey("file");
            if (file1) {
                final MultipartFile file2 = multipartRequest.getFile("file");
                try {
                    final String name = file2.getOriginalFilename();
                    final InputStream inputStream = file2.getInputStream();
                    String fileName = ControllerUtil.saveFile("/upload/brand", inputStream, name,IdUtil.fastSimpleUUID());
                    return fileName;
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    @RequestMapping("listBins")
    public String listBins(){

        return "/modular/recy/bins/bins_list.html";
    }
    @RequestMapping("binsList")
    @ResponseBody
    public Object binsList()
    {
        List<Bins> list = this.binsService.list();
        return list;
    }

    @RequestMapping("/gotoBins")
    public String gotoBins(String fromLocation,String toLocation,Model model){
        model.addAttribute("from",fromLocation.split(","));
        model.addAttribute("to",toLocation.split(","));
        return "/modular/recy/bins/bins_location.html";
    }

    @RequestMapping("/completeUserInfo")
    public String completeUserInfo(String code,Model model){
        boolean switchover = this.wxService.switchover(WxUtils.getDefaultMp());
        if(switchover){
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
            try {
                wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
                String openId = wxMpOAuth2AccessToken.getOpenId();
                WechatUser user = this.wechatUserService.findByOpenId(openId);
                model.addAttribute("user",user);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        Map<String,String> map  = new HashMap<>();
        map.put("id","123123");
        map.put("wechatNickName","asdf");
        model.addAttribute("user",map);
        return "/modular/recy/wechatUser/complete_user_info.html";
    }
    @RequestMapping("/saveUserInfo")
    @ResponseBody
    public Object saveUserInfo(){
        String userId = StringUtils.trim(this.getPara("userId"));
        if(StrUtil.isBlank(userId)){
            return new ErrorResponseData("请通过公众号发送的消息进入");
        }
        WechatUser user = this.wechatUserService.getById(Convert.toLong(userId));
        if(user==null){
            return new ErrorResponseData("用户不存在！");
        }
        String userName = StringUtils.trim(this.getPara("userName"));
        String phone = StringUtils.trim(this.getPara("phone"));
        String address = StringUtils.trim(this.getPara("remark"));
        if(StringUtils.isAnyBlank(userName,phone,address)){
            return new ErrorResponseData("姓名、手机、地址都不能为空！");
        }
        if(!Validator.isNumber(phone) || StrUtil.length(phone)!=11){
            return new ErrorResponseData("手机号码长度为11位！");
        }
        user.setUserName(userName);
        user.setPhone(phone);
        user.setRemark(address);
        this.wechatUserService.updateById(user);

        return new SuccessResponseData();
    }

    /**
     * 远程命令
     * @return
     */
    @RequestMapping("/commandList")
    @ResponseBody
    public Object commandList(@RequestHeader Long deviceId){
        Bins bins = binsService.getById(deviceId);
        if(bins!=null){
            bins.setLastUpdateTime(new DateTime());
            this.binsService.updateById(bins);
        }
        LambdaQueryWrapper<CommandOrder> commandOrderQueryWrapper = new LambdaQueryWrapper<>();
        commandOrderQueryWrapper.eq(CommandOrder::getBinsId,deviceId)
                                .eq(CommandOrder::getIsRead,0);
        List<CommandOrder> list = this.commandOrderService.list(commandOrderQueryWrapper);
        List<Map<String,Object>> mapList  = new ArrayList<>();
        for(CommandOrder commandOrder:list){
            Map<String,Object> map = new HashMap<>();
            CommandOrderVO commandOrderVO = EntityBind.bind(commandOrder, CommandOrderVO.class);
            Long wasteTypeId = commandOrder.getWasteTypeId();
            String commandSetStr = "";
            if(wasteTypeId!=null) {
                Integer commandSet = commandOrderVO.getWasteTypeIdModel().getCommandSet();
                commandSetStr = commandSet+"";
            }

            map.put("commandKey", commandSetStr +"_"+commandOrderVO.getCommandTag());
            map.put("commandObj",commandOrder);
            mapList.add(map);
        }
        return new SuccessResponseData(mapList);
    }

    @RequestMapping("/updateCommandStatus")
    @ResponseBody
    public Object updateCommandStatus(CommandOrder commandOrder){
        Long id = commandOrder.getId();
        CommandOrder commandOrder1 = this.commandOrderService.getById(id);
        if(commandOrder1!=null) {
            CopyOptions copyOptions = CopyOptions.create();
            copyOptions.setIgnoreNullValue(true);
            copyOptions.setIgnoreError(true);
            BeanUtil.copyProperties(commandOrder, commandOrder1, copyOptions);
            commandOrder1.updateById();
        }else{
            commandOrder1  = new CommandOrder();
        }
        return new SuccessResponseData(commandOrder1);
    }
    @RequestMapping("/queryUserByCardNo")
    @ResponseBody
    public Object queryUserByCardNo(@RequestHeader Long deviceId,String cardNo){
        if(StrUtil.isBlank(cardNo)){
            return new ErrorResponseData("卡号不能为空!");
        }
        QueryWrapper<UserBin> userBinQueryWrapper = new QueryWrapper<>();
        userBinQueryWrapper.lambda().eq(UserBin::getCardNo,cardNo);
        UserBin user = this.userBinService.getOne(userBinQueryWrapper, false);
        if(user==null){
            return new ErrorResponseData("该卡号未绑定，请先前往公众号绑定。");
        }
        QueryWrapper<WasteStation> wasteStationQueryWrapper = new QueryWrapper<>();
        wasteStationQueryWrapper.lambda().eq(WasteStation::getId,user.getWasteStationId());
        WasteStation wasteStation = this.wasteStationService.getOne(wasteStationQueryWrapper, false);
        if(wasteStation!=null&&wasteStation.getAreaCode().contains("330483")){
            org.joda.time.DateTime nowDateTime = new org.joda.time.DateTime();
            org.joda.time.DateTime startDateTime = nowDateTime.withTimeAtStartOfDay();
            Integer count = this.orderFormService.lambdaQuery()
                    .eq(OrderForm::getUserId, user.getUserId())
                    .between(OrderForm::getCreateTime,startDateTime.toDate(),nowDateTime.toDate())
                    .count();
            if(count>2){
                return new ErrorResponseData("今日已称重两次");
            }
        }

        UserBinVO userBinVO = EntityBind.bind(user, UserBinVO.class);
        WechatUser userIdModel = userBinVO.getUserIdModel();
        userIdModel.setCardNo(userBinVO.getCardNo());
        userBinVO.setUserIdModel(userIdModel);
        return new SuccessResponseData(userBinVO);
    }

    /*
    垃圾桶订单
     */
    @RequestMapping("/orderByUserBin")
    @ResponseBody
    public Object orderByUserBin(@RequestHeader Long deviceId,Long jifen,String cardNo,String weightStr,String isClean,String wasteStatus){
        //deviceId 称重设备id,canNo
        //将信息上传到第三方接口
        //transissom(deviceId);
        String fileName = savePhoto();
        if(StrUtil.isBlank(fileName)){
            return new ErrorResponseData("照片上传不成功！");
        }else if(Validator.isEmpty(cardNo) || !Validator.isNumber(weightStr)){
            return new ErrorResponseData("参数非法！");
        }
        else{
            BigDecimal bigDecimal = NumberUtil.toBigDecimal(weightStr);
            Long weight = bigDecimal.multiply(BigDecimal.valueOf(1000l)).longValue();
            Dict emptyBinsWeightDict = DictUtils.me().getDict("empty_bins_weight::weight");
            Long emptyBinsWeight = 3300l;
            if(emptyBinsWeightDict!=null) {
                emptyBinsWeight = Convert.toLong(emptyBinsWeightDict.getDescription(),3300l);
            }

            weight = weight-emptyBinsWeight;
            weight = weight<0?0:weight;
            QueryWrapper<UserBin> userBinQueryWrapper = new QueryWrapper<>();
            userBinQueryWrapper.lambda().eq(UserBin::getCardNo,cardNo);
            UserBin userBin = this.userBinService.getOne(userBinQueryWrapper, false);
            if(userBin!=null) {
                //long price = getIntegrate(userBin,weight,isClean,wasteStatus);

                /*{
                    UserBinVO userBinVO = EntityBind.bind(userBin,UserBinVO.class);
                    WechatUser userIdModel = userBinVO.getUserIdModel();
                    String areaCode = userIdModel.getAreaCode();
                    List<IntegrateInfo> integrateInfoList = this.integrateInfoService.lambdaQuery().eq(IntegrateInfo::getAreaCode, areaCode).nested(i -> i.eq(IntegrateInfo::getWasteTypeId, userBin.getWasteTypeId()).or().isNull(IntegrateInfo::getWasteTypeId)).list();
                    //重量回收
                    WasteType wasteType = this.wasteTypeService.getById(userBin.getWasteTypeId());
                    Integer jifenRate = Convert.toInt(wasteType.getTypeDesc(), 50);
                    price = weight / jifenRate;
                    if (!StrUtil.equals(wasteStatus, "0") || !StrUtil.equals(isClean, "1")) {
                        price = 0;
                    }
                    if (jifenRate > weight) {
                        price = 0;
                    }
                }*/
                Date submitTime = new Date();
                OrderForm orderForm = OrderForm.builder().userId(userBin.getUserId()).binsId(deviceId).wasteId(userBin.getWasteTypeId())
                        .state(DictUtils.me().id("order_form_state::finish")).finishTime(submitTime).createTime(submitTime)
                        .wasteWeight(weight)
                        .price(jifen)
                        .isClean(Convert.toInt(isClean))
                        .wasteStatus(Convert.toInt(wasteStatus))
                        .orderNo(fileName)
                        .build();
                orderForm.insert();
                Long userId = orderForm.getUserId();
                if(jifen>0L) {

                    if (userId != null) {
                        WechatUser user = this.wechatUserService.getById(userId);
                        user.setWithdraw(user.getWithdraw() + orderForm.getPrice());//积分
                        user.insertOrUpdate();
                    }
                }
                WechatUser user = this.wechatUserService.getById(userId);
                WasteStation station = this.wasteStationService.getById(userBin.getWasteStationId());

                if(station.getAreaCode().contains("3304831012")){
                    JSONObject param=new JSONObject();
                    param.put("sign","garbage_system");

                    param.put("picUrl","http://recy.jinbaoiot.com/upload/brand/"+orderForm.getOrderNo());

                    String wasteId=orderForm.getWasteId().toString();

                    switch (wasteId){
                        case "1200219562407469058": param.put("garbageType",2);break;
                        case "1200220025915809794": param.put("garbageType",3);break;
                        case "1203216857021874177": param.put("garbageType",4);break;
                        default:param.put("garbageType",1);break;

                    }
                    param.put("localTime",orderForm.getCreateTime());
                    param.put("sysOrgCode",station.getZzdeptName());
                    param.put("kioskId",station.getZzStationId());
                    Bins bin=binsService.getById(deviceId);
                    param.put("deviceName","无");
                    param.put("weight", Double.parseDouble(orderForm.getWasteWeight()+"")/1000);
                    param.put("faceUrl","无");
                    param.put("faceDiscemResult","无");
                    param.put("sysUserId",user.getZzid());
                    param.put("cardNumber",user.getId());
                    param.put("barrelStatus",0);
                    param.put("supervisorName",station.getStationName());
                    param.put("supervisorPhone",station.getMgrPhone());
                    param.put("resultType",1);
                    param.put("interveneStatus",orderForm.getIsClean());
                    if(orderForm.getIsClean()==1){
                        param.put("aiResultId",0);
                    }else {
                        param.put("aiResultId",1);
                    }
                    param.put("faceDiscernResult","无");

                    param.put("aiResult",orderForm.getWasteStatus());
                    param.put("supervisorResult",1);
                    aigoesGarbageRecordThirdPush(param);
                }



                ImmutableMap<String, ? extends Serializable> map = ImmutableMap.of("price", orderForm.getPrice(), "msg", "回收成功，减去桶重"+emptyBinsWeight+"克，净重：" + weight + "克，获得" + orderForm.getPrice() + "积分；");
                return new SuccessResponseData(map);
            }else{
                return new ErrorResponseData("卡号未绑定！");
            }
        }
    }


    /**
     *
     */
    @RequestMapping("/getImformation")
    public JSONObject getImformation(String sign, String deptName){
        JSONObject result = new JSONObject(); //承接结果的JSONObject
        JSONObject jsonObject = findByParentName(sign,deptName);
        com.alibaba.fastjson.JSONArray zz = (com.alibaba.fastjson.JSONArray) jsonObject.get("result");
        JSONObject area = (JSONObject) zz.get(0);
        String deptId = area.getString("deptId");
        String departName = area.getString("departName");
        QueryWrapper<WechatUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("area",departName);
        List<WechatUser> users = wechatUserService.list(queryWrapper);
        JSONObject param = new JSONObject();
        for(WechatUser user: users){
            param.put("sign",sign);
            param.put("departName",departName);
            param.put("homeAddr",user.getRemark());
            param.put("isMaster",1);
            param.put("realname",user.getUserName());
            param.put("telephone",user.getPhone());
            param.put("pointCard",user.getId());
            param.put("politicalOutlook",1);
            param.put("isCivilServant",0);
            param.put("isEmptyHome",0);
            param.put("sysOrgCode",deptId);
            result = aigoesRuralHomeUserThirdPush(param);
            if(result.get("code").equals(200) || result.get("code") == "200"){
                user.setZzid(result.get("message").toString());
                wechatUserService.updateById(user);
                System.out.println(user.getUserName()+"导入成功"+result.get("code"));
            }else{
                System.out.println(user.getUserName()+"导入失败"+result.get("code")+result.get("message"));
            }
        }
        return result;
    }


    public JSONObject findByParentName(String sign, String deptName){
        //使用http请求第三方接口
        String url = "http://125.124.3.200:7777/garbage/api/zhenCang/findByParentName"+"?sign="+sign+"&deptName="+deptName;
        JSONObject zz = Utils.doGet(url);
        return zz;
    }
    /*
    * 传输订单信息
    * */
    public void aigoesGarbageRecordThirdPush( JSONObject params){
        String url = "http://218.0.50.251:80/garbage/api/zhenCang/aigoesGarbageRecordThirdPush";


        JSONObject result = Utils.doPost(url,params);
        System.out.println(result);
    }
    /**
     * 这是第二个三方接口，用于用户数据插入
     */
    //@RequestMapping("/aigoesRuralHomeUserThirdPush")
    //@ResponseBody
    public JSONObject aigoesRuralHomeUserThirdPush(JSONObject params){
        JSONObject jsonObject = params;
        //  int size = jsonObject.
        if(jsonObject!=null){
            jsonObject.get("id");
        }
        QueryWrapper<WechatUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.select();
        String url = "http://218.0.50.251:80/garbage/api/zhenCang/aigoesRuralHomeUserThirdPush";
        JSONObject result = Utils.doPost(url,params);
        return result;
    }

    /**
     * 第三个接口
     * @return
     */
    @RequestMapping("/aigoesKioskThirdPush")
    @ResponseBody
    public JSONObject aigoesKioskThirdPush(String sign,String deptName){
        String url = "http://218.0.50.251:80/garbage/api/zhenCang/aigoesKioskThirdPush";
        //定义返回
        JSONObject result = new JSONObject();
        //定义参数
        JSONObject params = new JSONObject();
        QueryWrapper<WasteStation> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("address",deptName);
        List<WasteStation> wasteStations = wasteStationService.list(queryWrapper);
        for(WasteStation wasteStation:wasteStations){
            User user = userService.getById(wasteStation.getMgrUserId());
            params.put("sign","garbage_system");
            params.put("linkman",user.getName());
            params.put("phone",wasteStation.getMgrPhone());
            params.put("name",wasteStation.getStationName());
            params.put("location",wasteStation.getAddress());
            params.put("productDate",new Date());
            int index = wasteStation.getGps().indexOf(",");
            params.put("lng",wasteStation.getGps().substring(0,index));
            params.put("lat",wasteStation.getGps().substring(index+1,wasteStation.getGps().length()));
            JSONObject jsonObject = findByParentName(sign,deptName);
            com.alibaba.fastjson.JSONArray zz = (com.alibaba.fastjson.JSONArray) jsonObject.get("result");
            JSONObject area = (JSONObject) zz.get(0);
            String deptId = area.getString("deptId");
            params.put("sysDepartId",deptId);
            result = Utils.doPost(url,params);
            if(result.get("code").equals(200) || result.get("code") == "200"){
                wasteStation.setZzStationId(result.get("result").toString());
                wasteStationService.updateById(wasteStation);
                System.out.println(wasteStation.getMgrPhone()+"导入成功"+result.get("code"));
            }else{
                System.out.println(wasteStation.getMgrPhone()+"导入失败"+result.get("code")+result.get("message"));
            }
        }
        return null;
    }

    /**
     * 四
     * @return
     */
    @RequestMapping("/aigoesGarbageRecordThirdPush")
    @ResponseBody
    public JSONObject aigoesGarbageRecordThirdPush(String sign,String deptName){
        String url1 = "http://218.0.50.251:80/garbage/api/zhenCang/aigoesGarbageRecordThirdPush";
        //定义返回
        JSONObject result = new JSONObject();
        //定义参数
        QueryWrapper<WechatUser> wechatUserQueryWrapper = new QueryWrapper<>();
        wechatUserQueryWrapper.like("area",deptName);
        List<WechatUser> wechatUsers = wechatUserService.list(wechatUserQueryWrapper);
        for(WechatUser wechatUser:wechatUsers) {
            JSONObject param = new JSONObject();
            QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("user_id",wechatUser.getId());
            List<OrderForm> orderForms = orderFormService.list(queryWrapper);
            for(OrderForm orderForm:orderForms){
                WechatUser user=wechatUserService.getById(orderForm.getUserId());
                QueryWrapper<UserBin> userBinQueryWrapper = new QueryWrapper<>();
                userBinQueryWrapper.like("user_id",user.getId());
                List<UserBin> userBins=userBinService.list(userBinQueryWrapper);

                WasteStation wasteStation=wasteStationService.getById(userBins.get(0).getWasteStationId());

                param.put("sign","garbage_system");

                param.put("sysOrgCode",wasteStation.getZzdeptName());
                param.put("picUrl","http://recy.jinbaoiot.com/upload/brand/"+orderForm.getOrderNo());

                String wasteId=orderForm.getWasteId().toString();

                switch (wasteId){
                    case "1200219562407469058": param.put("garbageType",2);break;
                    case "1200220025915809794": param.put("garbageType",3);break;
                    case "1203216857021874177": param.put("garbageType",4);break;
                    default:param.put("garbageType",1);break;

                }
                param.put("localTime",orderForm.getCreateTime());

                param.put("kioskId",wasteStation.getZzStationId());
                Bins bin=binsService.getById(orderForm.getBinsId());
                param.put("deviceName","无");
                param.put("weight",Double.parseDouble(orderForm.getWasteWeight()+"")/1000);
                param.put("faceUrl","无");
                param.put("sysUserId",user.getZzid());
                param.put("barrelStatus",0);
                param.put("supervisorName",wasteStation.getStationName());
                param.put("supervisorPhone",wasteStation.getMgrPhone());
                param.put("resultType",1);
                param.put("interveneStatus",orderForm.getIsClean());
                if(orderForm.getIsClean()==1){
                    param.put("aiResultId",0);
                }else {
                    param.put("aiResultId",1);
                }
                param.put("supervisorResult",1);
                param.put("faceDiscernResult","无");
                param.put("cardNumber",user.getId());
                result = Utils.doPost(url1,param);
               // System.out.println(result);
                if(result.get("code").equals(200) || result.get("code") == "200"){

                    //System.out.println(param.toJSONString());
                    System.out.println(user.getUserName()+"导入成功"+result.get("code"));
                }else{
                   // System.out.println(param.toJSONString());
                    System.out.println(user.getUserName()+"导入失败"+result.get("code")+result.get("message"));
                }
            }
        }

        return null;
    }
    private long getIntegrate(UserBin userBin,long weight,String isClean,String wasteStatus){
        long price = 0L;
        {
            if (!StrUtil.equals(wasteStatus, "0") || !StrUtil.equals(isClean, "1")) {
                price = 0L;
            }else {
                UserBinVO userBinVO = EntityBind.bind(userBin, UserBinVO.class);
                WechatUser userIdModel = userBinVO.getUserIdModel();
                String areaCode = userIdModel.getAreaCode();
                List<IntegrateInfo> integrateInfoList = this.integrateInfoService.lambdaQuery().eq(IntegrateInfo::getAreaCode, areaCode).nested(i -> i.eq(IntegrateInfo::getWasteTypeId, userBin.getWasteTypeId()).or().isNull(IntegrateInfo::getWasteTypeId)).list();
                int integrateType = 0;//0：重量，1：次数
                if (integrateInfoList.size() > 0) {
                    IntegrateInfo integrateInfo = integrateInfoList.get(0);
                    Integer jifenRate = integrateInfo.getIntegrateVal().intValue();
                    if (DictUtils.me().eq("integrate_type::weight", integrateInfo.getIntegrateType())) {
                        //重量回收
                        //WasteType wasteType = this.wasteTypeService.getById(userBin.getWasteTypeId());
                        //Convert.toInt(wasteType.getTypeDesc(), 50);

                        /*if (!StrUtil.equals(wasteStatus, "0") || !StrUtil.equals(isClean, "1")) {
                            price = 0;
                        }*/
                        if (jifenRate > weight) {
                            price = 0L;
                        }else{
                            price = weight / jifenRate;
                        }
                    } else {
                        //次数回收
                        price = jifenRate;
                        integrateType = 1;
                    }
                } else {
                    //默认次数回收
                    Dict timeDict = DictUtils.me().getDict("integrate_type::time");
                    String description = timeDict.getDescription();
                    price = NumberUtils.toLong(description);
                    integrateType = 1;
                }
                if(integrateType==1){
                    org.joda.time.DateTime nowDateTime = new org.joda.time.DateTime();
                    org.joda.time.DateTime startDateTime = nowDateTime.withTimeAtStartOfDay();
                    Integer count = this.orderFormService.lambdaQuery()
                                    .eq(OrderForm::getUserId, userBin.getUserId())
                                    .between(OrderForm::getCreateTime,startDateTime.toDate(),nowDateTime.toDate())
                                    .count();
                    if(new Integer(2).compareTo(count)<=0){
                        price =0L;
                    }
                }
            }

        }
        return price;
    }
    public String getPosition(){
        return null;
    }

    @RequestMapping("/apk")
    public Object apk(){
        return "/modular/recy/app/apk.html";
    }

    private String getArea(){
        String ip = ServletUtil.getClientIP(this.getHttpServletRequest());
        String json = HttpUtil.get("http://freeapi.ipip.net/" + ip);
        JSONArray areas = JSONUtil.parseArray(json);
        String join = areas.join(",");
        return join;
    }

    private Map<String,String> getSign(){
        Map<String,String> signMap = new HashMap<>();
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        String deviceId = httpServletRequest.getHeader("deviceId");
        signMap.put("deviceId",deviceId);
        String timestamp = httpServletRequest.getHeader("timestamp");
        signMap.put("timestamp",timestamp);
        String nonce = httpServletRequest.getHeader("nonce");
        signMap.put("nonce",nonce);
        String sign = httpServletRequest.getHeader("sign");
        signMap.put("sign",sign);
        return signMap;
    }
}
